/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.customer;

import app.Const;
import app.models.DaoKit;
import app.models.member.Member;
import app.models.member.TicketOptRecord;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DataSet;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.controller.datatables.core.DatatablesResponse;
import com.github.sog.controller.security.Securitys;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.primitives.Doubles;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.BooleanUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-10 21:47
 * @since JDK 1.6
 */
public class MemberController extends BasicController {


    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        Member member = getModel(Member.class);

        final DatatablesCriterias criterias = getCriterias();
        if (member == null || member.getAttrNames().length == 0) {
            renderEmptyDataTables(criterias);
            return;
        }
        Page<Member> memberPage = Member.dao.customer_members(criterias, member);
        if (memberPage == null) {
            renderEmptyDataTables(criterias);
            return;
        }
        renderDataTables(memberPage, criterias);
    }


    public void show() {
        setAttr("member", Member.dao.findById(getPara()));
        render("show.ftl");
    }


    public void ticker() {
        long memberId = getParaToLong("member", 0l);
        String integral = getPara("integral");

        final String param_ticket = getPara("ticket");
        if (Strings.isNullOrEmpty(integral) || Strings.isNullOrEmpty(param_ticket)) {
            renderError("请输入小票号和积分值在重试!");
            return;
        }
        if (TicketOptRecord.dao.findByTicketNo(param_ticket) != null) {
            renderJson(AjaxMessage.failure("兑换失败，小票号输入重复"));
            return;
        }
        long customer = Securitys.getLoginMember().getId();
        final double double_integral = Objects.firstNonNull(Doubles.tryParse(integral), 0.0);
        if (TicketOptRecord.dao.customerRecord(memberId, customer, double_integral, param_ticket)) {
            renderJson(AjaxMessage.ok("兑换成功"));
        } else {
            renderError("小票积分兑换失败，请联系管理员!");
        }
    }

    public void create() {
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr("member", Member.dao);
        render("item.ftl");
    }

    public void edit() {
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr("member", Member.dao.findById(getPara()));
        render("item.ftl");
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        List<Member> update_members = Lists.newArrayList();
        for (String id : ids) {
            Member _member = new Member();
            _member.set(AppFunc.TABLE_PK_COLUMN, id);
            update_members.add(_member);
        }
        if (DaoKit.batch_update(SqlKit.sql("member.delete"), update_members)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

    public void checkno() {

        Member member = getModel(Member.class);
        final Number number = member.getNumber(AppFunc.TABLE_PK_COLUMN);
        boolean exist_no = Member.dao.exist_card_no(member.getStr("card_no"), (number == null) ? 0 : number.longValue());
        renderText(BooleanUtils.toStringTrueFalse(exist_no));
    }

    public void save() {
        Member member = getModel(Member.class);
        if (DaoKit.isNew(member)) {
            member.set("create_time", DateProvider.DEFAULT.getCurrentDate());
            member.set("create_user", Securitys.getLoginMember().getName());
//            member.set("card_no", Sn.dao.member());
            member.set("temp", false);
            member.save();
            // todo 微信端会员注册需要发送短信
//                SmsWsKit.membreApplySend(member.getStr("phone"), RandomStringKit.randomNumeric(8), 30);


        }
        redirect("/customer/member");
    }

    protected void renderEmptyDataTables(DatatablesCriterias criterias) {
        Preconditions.checkNotNull(criterias, "datatable criterias is must be not null.");
        DataSet dataSet = DataSet.newSet(Collections.EMPTY_LIST, 0l, 0l);
        DatatablesResponse response = DatatablesResponse.build(dataSet, criterias);
        renderJson(response);
    }
}